﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;

namespace Defecter.Server
{
	#region Class DefecterService
	public class DefecterService: ServiceBase
	{
		#region DefecterService - Types
		#endregion

		#region DefecterService - Fields
		static private DefecterService	ds_instance;
		private bool										ds_is_service;
		#endregion

		#region DefecterService - Delegates and Events
		#endregion

		#region DefecterService - Properties
		static public DefecterService Instance
		{
			get
			{
				if (ds_instance == null)
					ds_instance = new DefecterService();
				return ds_instance;
			}
		}		/* property Instance */

		public bool IsService
		{
			get
			{
				return ds_is_service;
			}
		}		/* property DefecterService IsService */
		#endregion

		#region DefecterService - Constructors
		private DefecterService ()
		{
			ds_is_service = true;
			ServiceName = "DefecterService";
			CanHandlePowerEvent = false;
			CanPauseAndContinue = false;
			CanShutdown = true;
			CanStop = true;
		}		/* constructor DefecterService */
		#endregion

		#region DefecterService - Methods
		static void Main (string[] args)
		{
			DefecterService	ds;

			if (Array.IndexOf(args, "-debug") >= 0 ||
				Array.IndexOf(args, "/debug") >= 0)
			{
				Console.WriteLine("Use Ctrl-C to terminate");
				try
				{
					ds = DefecterService.Instance;
					ds.ds_is_service = false;
					try
					{
						ds.OnStart(args);
						Console.ReadLine();
					}
					catch (Exception ex)
					{
						Console.WriteLine("Global exception {0}", ex);
					}
					finally
					{
						Console.WriteLine("Falling in OnStop");
						try
						{
							ds.OnStop();
						}
						catch (Exception ex)
						{
							Console.WriteLine("OnStop failed with {0}", ex);
							Console.WriteLine(ex.StackTrace);
						}
					}

				}
				catch (Exception ex)
				{
					Console.WriteLine("Could not create Defecter Service object");
					Console.WriteLine("Exception {0}", ex);
					Console.WriteLine(ex.StackTrace);
				}
			}
			else
				System.ServiceProcess.ServiceBase.Run(DefecterService.Instance);
		}		/* method Main */

		protected override void OnShutdown ()
		{
			base.OnShutdown();
		}		/* method OnShutdown */

		protected override void OnStart (string[] args)
		{
			base.OnStart(args);

/*
 *			Fire up the client connection interface
 * */
			ClientContractImpl.Activate();
		}		/* method OnStart */

		protected override void OnStop ()
		{
			base.OnStop();
			if (ClientContractImpl.Instance != null)
				ClientContractImpl.Instance.DeActivate();
		}		/* method OnStop */
		#endregion

	}
	#endregion
}
